<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let input = `-3 12 6 8 9 -10 -7
        8 12 -3 6 -10 9 -7`
        let [mid, first] = input.split('\n').map(v => v.trim().split(' ').map(j => parseInt(j)))

        class TreeNode {
            constructor(value) {
                this.value = value
                this.left = null
                this.right = null
            }
        }
        function biuldTree(midlis, firstlis) {
            if (midlis.length == 0 || firstlis.length == 0) {
                return null
            }
            let rootValue = firstlis[0];
            let count = 0;  

            let mid_index = midlis.indexOf(rootValue);   
            midlis.forEach(v => count+= v)         
            rootValue = count - rootValue            
            let root = new TreeNode(rootValue)            
            
            // 中序遍历左右子树列表    
            let mid_left = midlis.slice(0, mid_index)
            let mid_right = midlis.slice(mid_index + 1, midlis.length)

            // 先序遍历左右子树列表
            let first_left = firstlis.slice(1, mid_index + 1)
            let first_right = firstlis.slice(mid_index + 1, firstlis.length)

            root.left = biuldTree(mid_left, first_left)
            root.right = biuldTree(mid_right, first_right)
            return root

        }
        let tree = biuldTree(mid, first)

        let res=[]

        function midfoo(node){
            if(node.left){
                midfoo(node.left)
            }
            res.push(node.value);
            if(node.right){
                midfoo(node.right)
            }           

        }

        midfoo(tree)
        console.log(...res);
        


        

    </script>
</body>

</html>